import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import Viewer from "viewerjs";
import "viewerjs/dist/viewer.css";
import "./css/ImgPreview.less";

interface ImgPreviewProps {
    defaultKey?: string,
    file: string,
    fileList: string,
    previewKey: string
}

const ImgPreview: FC<ImgPreviewProps> = (props) => {
    const imgBoxRef = useRef();

    const viewerRef = useRef();

    const [list, setList] = useState<any[]>([]);

    const initImg: Function = useCallback(() => {
        viewerRef.current = new Viewer(imgBoxRef.current, {
            inline: true,
            button: false,
            toolbar: {
                play: false,
                prev: true,
                next: true,
                rotateLeft: true,
                rotateRight: true,
                flipHorizontal: true,
                flipVertical: true,
                zoomIn: true,
                zoomOut: true,
            }
        });
    }, []);


    const loadImg: Function = useCallback(() => {
        if (props.file) {
            setList([props])
        } else if (props.fileList) {
            setList(props.fileList)
        }
    }, [props]);

    useEffect(() => {
        initImg();
    }, []);

    useEffect(() => {
        if (list.length) {
            let index: number = list.findIndex((i: any) => (i.id === props.defaultKey));
            index = index === -1 ? 0 : index;
            viewerRef.current?.update();
            viewerRef.current?.view(index);
            let navbar: any = viewerRef.current?.navbar;
            if (list.length === 1) {
                navbar && (navbar.style.display = "none");
            } else {
                navbar && (navbar.style.display = "block");
            }
        }
    }, [list, props.defaultKey]);

    useEffect(() => {
        loadImg();
    }, [props.previewKey]);

    const renderImgPreview = useMemo(() => {
        return (
            <div className={"sf_core_img_preview"}>
                <div ref={imgBoxRef}>
                    {list.map((item: any) => {
                        return <img alt={item.fileName} src={item.file} key={item.previewKey}
                                    style={{display: "none"}}/>
                    })}
                </div>
            </div>
        )
    }, [list]);

    return (renderImgPreview);
};

export default React.memo(ImgPreview);